#include"RecFrameServer.h"
#include"../DataDecoding/DataDecoding.h"
RecFrameServer::RecFrameServer(int flag):HServerBase(flag)
{
    status = false;
    dataDecoder = new DataDecoding(AV_CODEC_ID_H264,this);
}
RecFrameServer::~RecFrameServer(){
    delete dataDecoder;
}
// 暂未考虑包错位的情况
int RecFrameServer::rcv_frame_packet(string &data)
{
    auto start_time = std::chrono::high_resolution_clock::now();
    data.clear();
    int rcvSize = 0;
    SendFrameCliMsg::FrameMsg frameMsg;
    string aPacket;
    rcvSize += recvData(aPacket,sock->s,cli);
    {
        frameMsg.ParseFromString(aPacket);
    }
    //只有一个包
    if(frameMsg.flag() == 3){
        data = frameMsg.framedata();
        cout<<"rcv a frame:"<<data.size()<<endl;
        auto end_time = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
        std::cout << "rcv time: " << static_cast<double>(duration.count()) / 1e6<< " s" << std::endl;
        return rcvSize;
    }
    //多个包
    data += frameMsg.framedata();
    int i = 0;
    while(frameMsg.flag() != 2){
        rcvSize += recvData(aPacket,sock->s,cli);
        {
            frameMsg.ParseFromString(aPacket);
        }
        data += frameMsg.framedata();
    }
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
    cout<<"rcv a frame:"<<data.size()<<endl;
    std::cout << "rcv time: " << static_cast<double>(duration.count()) / 1e6<< " s" << std::endl;
    return rcvSize;
}

int RecFrameServer::startServer()
{
    status = true;
    string data;
    //1 握手(确认对方正常)
    int len = recvData(data,sock->s,cli);
    cout<<"sendFramecli:"<<data<<endl;
    if(data != "Hello!"){
        cout<<"握手异常！"<<endl;
        status = false;
        //TODO:解析data
        return -1;
    }
    std::cout << "cli Port: " << ntohs(cli.sin_port) << std::endl;
    //2 回复
    sendData("OK",sock->s,cli);
    //新开线程解码
    std::thread t1(&DataDecoding::run,dataDecoder);
    t1.detach();
    int i = 1;
    //3 开始接收
     while(status){
        //1 解析
         cout<<"rcv id:"<<i++<<endl;
        int ret = rcv_frame_packet(data);
        //2 将编码数据存入
        EncodeBuffer* encoderbuffer = new EncodeBuffer(data.size());
        memcpy(encoderbuffer->encoderFramePtr,data.c_str(),data.size());
        encodeStreams.Push(encoderbuffer);
    }
     encodeStreams.Clear();
    status = false;
    sock->Hclose();
    cout<<"RecFrameServer close!"<<endl;
    return 0;
}

void RecFrameServer::stopServer()
{
    this->status = false;
}


